package com.lzy.user.controller;

import com.lzy.api.controller.user.BaseController;
import com.lzy.api.controller.user.PastportControllerApi;
import com.lzy.enums.UserStatus;
import com.lzy.grace.result.GraceJSONResult;
import com.lzy.grace.result.ResponseStatusEnum;
import com.lzy.pojo.AppUser;
import com.lzy.pojo.bo.RegistLoginBO;
import com.lzy.user.service.UserService;
import com.lzy.utils.IPUtil;
import com.lzy.utils.MyInfo;
import com.lzy.utils.RedisOperator;
import com.lzy.utils.SMSUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
public class PastportController extends BaseController implements PastportControllerApi {

    final static Logger logger = LoggerFactory.getLogger(PastportController.class);

    @Autowired
    private SMSUtils smsUtils;
    @Autowired
    private RedisOperator redis;
    @Autowired
    private UserService userService;
    @Override
    public GraceJSONResult getSMSCode(String mobile, HttpServletRequest request) {

        // 根据用户的ip来限制用户在60秒内只能获得一次验证吗。
        String userIP = IPUtil.getRequestIp(request);

        // value随意填写即可，因为仅仅只是用来锁住ip的，60秒过后，又能发送了
        // 也就是说，这个key存在，则当前ip用户无法发送验证码，直到key消失
        redis.setnx60s(MOBILE_SMSCODE + ":" + userIP, userIP);

//        if (mobile.equalsIgnoreCase("123456")) {
//            mobile = MyInfo.getMobile();
//        }
        String random = (int)((Math.random() * 9 + 1) * 100000) + "";
        // 把验证码放入redis，并且锁住用户的ip为60秒，60秒内无法再次发送验证码
        System.out.println(mobile);
        redis.set(MOBILE_SMSCODE + ":" + mobile, random, 30*60);

       // smsUtils.sendSMS(mobile, random);

        return GraceJSONResult.ok();
    }

    @Override
    public GraceJSONResult doLogin(HttpServletRequest request, HttpServletResponse response, RegistLoginBO registerLoginBO, BindingResult result) {
        //1. 判断BindingResult是否保存错误的验证信息，如果有，则直接return
        if (result.hasErrors()) {
            Map<String, String> errorMap = getErrors(result);
            return GraceJSONResult.errorMap(errorMap);
        }

        //2. 获得前端传来的基本信息
        String smsCode = registerLoginBO.getSmsCode();
        String mobile = registerLoginBO.getMobile();

        //3. 校验验证码是否匹配 (为空或者不匹配)
        String redisSMSCode = redis.get(MOBILE_SMSCODE + ":" +mobile);
        if (StringUtils.isBlank(redisSMSCode) || !redisSMSCode.equalsIgnoreCase(smsCode)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.SMS_CODE_ERROR);
        }

        //4. 查询数据库，该用户是否注册过
        AppUser user = userService.queryMobileIsExist(mobile);
        if (user != null && user.getActiveStatus() == UserStatus.FROZEN.type) {
            // 5. 如果用户不为空并且状态已经冻结，则直接抛出异常，无法登录
            return GraceJSONResult.errorCustom(ResponseStatusEnum.USER_FROZEN);
        } else if (user == null) {
            // 6. 如果没有注册过，注册用户信息入库，用户状态未激活
            user = userService.createUser(mobile);
        }

        int userActiveStatus = user.getActiveStatus();
        //7. 如果用户状态已经被封了，则不设置会话与cookie信息
        if (userActiveStatus != UserStatus.FROZEN.type) {
            // 8. 用户的分布式会话设置
            String uniqueToken = UUID.randomUUID().toString().trim();
            redis.set(REDIS_USER_TOKEN + ":" + user.getId(), uniqueToken);

            // 9. 用户userId与token放入cookie
            setCookie(request, response, "utoken", uniqueToken, COOKIE_MONTH);
            setCookie(request, response, "uid", user.getId(), COOKIE_MONTH);
        }

        // 10. 用户登录成功则需要删除已经使用过的短信验证码，该验证码只能匹配使用一次，过后作废
          redis.del(MOBILE_SMSCODE + ":" + mobile);

        // 11. 用户状态：未激活或者已激活，返回给前端，用于页面跳转
            return GraceJSONResult.ok(userActiveStatus);

       // return GraceJSONResult.ok(user);
    }

    @Override
    public GraceJSONResult updateUserInfo(String userId,
                                          HttpServletRequest request,
                                          HttpServletResponse response) {
        //用户退出登录,删除redis里面的token信息并且cookie里面的值清空
        redis.del(REDIS_USER_TOKEN + ":" + userId);
        setCookie(request,response,"utoken","",COOKIE_DELETE);
        setCookie(request,response,"uid","",COOKIE_DELETE);

        return GraceJSONResult.ok();
    }


    /**
     * 验证beanBO中的字段错误信息
     * @param result
     * @return
     */



}
